package com.yitiao.data_algorithms.leetcode.editor.cn;

import com.yitiao.data_algorithms.leetcode.editor.cn.base.TreeNode;

import java.util.ArrayList;
import java.util.List;

class BalanceABinarySearchTree {
    // 2023-02-08 17:06:00
    public static void main(String[] args) {
        Solution solution = new BalanceABinarySearchTree().new Solution();
    }

    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        // 中序遍历 + 二分
        List<Integer> nums;

        public TreeNode balanceBST(TreeNode root) {
            nums = new ArrayList<>();
            dfs(root);
            return buildTree(0, nums.size() - 1);
        }

        private TreeNode buildTree(int l, int r) {
            if (r - l < 0) {
                return null;
            }
            int mid = l + (r - l) / 2;
            TreeNode treeNode = new TreeNode(nums.get(mid));
            treeNode.left = buildTree(l, mid - 1);
            treeNode.right = buildTree(mid + 1, r);
            return treeNode;
        }

        private void dfs(TreeNode root) {
            if (root == null) return;
            dfs(root.left);
            nums.add(root.val);
            dfs(root.right);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}